/**
 * Created by mkDark on 2017/11/18.
 */
var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var YjxBaseModel = require('./YjxBaseModel');
var CONFIG = require('../../config');



var YjxThirdPartyUserModel = function (obj) {
    YjxBaseModel.call(this, obj);

    /*
     CREATE TABLE `yjx_third_party_user` (
     `tpu_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '第三方账号id',
     `user_id` bigint(20) DEFAULT NULL COMMENT '关联的用户主表id (yjx_user.user_id)',
     `account_type` int(3) NOT NULL DEFAULT '0' COMMENT '第三方账号类型: 0:未知, 10:手机号(需要密码), 11:邮箱(需要密码), 20:微信, 21:QQ, 30:小米, 100:一键生成',
     `nickname` varchar(50) DEFAULT NULL COMMENT '第三方账号昵称',
     `profile_photo` varchar(500) DEFAULT NULL COMMENT '第三方账号头像url',
     `field1` varchar(1000) DEFAULT NULL COMMENT '字段1(根据账号类型而不同): 手机:手机号码, 邮箱:Email地址, 微信:UnionId, QQ:QQ号, 小米:UserId, 一键生成:itb_user.user_id',
     `field2` varchar(1000) DEFAULT NULL COMMENT '字段2: 手机:区号, 微信:OpenId, 小米:OpenId',
     `field3` varchar(1000) DEFAULT NULL COMMENT '字段3',
     `field4` varchar(1000) DEFAULT NULL COMMENT '字段4',
     `field5` varchar(1000) DEFAULT NULL COMMENT '字段5',
     `create_time` datetime NOT NULL COMMENT '创建时间',
     `update_time` datetime NOT NULL COMMENT '更新时间',
     `update_by` varchar(50) DEFAULT NULL COMMENT '更新者',
     `del_flg` int(11) NOT NULL DEFAULT '0' COMMENT '逻辑删除标志位',
     PRIMARY KEY (`tpu_id`)
     ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COMMENT='第三方账号表'
     */
};

YjxThirdPartyUserModel.prototype = new YjxBaseModel();

// 取得表名
YjxThirdPartyUserModel.prototype.getTableName = function(){
    return 'yjx_third_party_user';
};
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
YjxThirdPartyUserModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'tpu_id='+this.tpu_id;
};



//------------------------------------------------------------------
/* 根据手机号获取第三方用户信息
 * 参数:accountType: 账号类型(如:10手机)
 * 参数:keyField: 关键字段,默认为field1(如:手机号码13000000000)
 * 参数:callback:回调
 * */
YjxThirdPartyUserModel.prototype.getInfoByAccountKey = function(accountType, keyField, callback){
    var THIS = this;

    pool.pool.getConnection(function(err, connection) {
        var sql = ' SELECT t.* '+
            ' FROM yjx.yjx_third_party_user t '+
            ' WHERE t.del_flg=0 AND t.account_type='+accountType+' AND t.field1=?'+
            ' ORDER BY t.tpu_id DESC ';

        var sqlValue = [keyField];
        sql = mysql.format(sql, sqlValue);

        console.log(sql);
        connection.query(sql, function(error, result){
            connection.release();

            callback(error, result);
        });
    });
};

// 关联组织信息
YjxThirdPartyUserModel.prototype.getInfoByAccountKeyWithOrg = function(accountType, keyField, callback){
    var THIS = this;

    pool.pool.getConnection(function(err, connection) {
        var sql = ' SELECT t.*, o.type AS org_type, r.org_id, r.role, r.desc AS r_desc '+
            ' FROM yjx.yjx_third_party_user t '+
            ' LEFT JOIN yjx.yjx_org_r r ON r.user_id=t.user_id AND r.state=10 AND r.del_flg=0 '+
            ' LEFT JOIN yjx.yjx_org o ON o.org_id=r.org_id AND o.del_flg=0 '+
            ' WHERE t.del_flg=0 AND t.account_type='+accountType+' AND t.field1=?'+
            ' ORDER BY t.tpu_id DESC, r.create_time DESC ';

        var sqlValue = [keyField];
        sql = mysql.format(sql, sqlValue);

        console.log(sql);
        connection.query(sql, function(error, result){
            connection.release();

            callback(error, result);
        });
    });
};

/**
 * 为修正1.0 iOS 微信登录误传 openId 至 unionId 的位置所做的兼容操作, 仅限 1.0 三方登录接口使用, 其他勿用
 *
 * @author 王俊
 * @date 2017-12-26
 *
 * @param openId    微信用户的 openId
 * @param callback  回调
 *          error:  查询失败
 *          user:   可能存在可能不存在
 *             tpu.*        第三方用户所有列
 *             rightUser:   field1 存入的是 unionId 则 rightUser = 1
 */
YjxThirdPartyUserModel.prototype.checkWechatUserIsExistsForV1_0 = function (openId, callback) {

    pool.pool.getConnection(function(getConnectErr, connection) {
        if (getConnectErr) {
            console.log('YjxThirdPartyUserModel.checkWechatUserIsExistsForV1_0 getConnectErr: ' + getConnectErr);
            return callback(getConnectErr, null);
        }
        var sql =' SELECT ytpu.*, ' +
            '        IF (ytpu.field1 = "'+openId+'",0,1) AS rightUser ' +
            ' FROM yjx.yjx_third_party_user ytpu ' +
            ' WHERE ytpu.del_flg=0 ' +
            '   AND (ytpu.field1 = "'+openId+'" ' +
            '        OR ytpu.field2 = "'+openId+'")' +
            '   AND ytpu.account_type = 20 ';

        console.log(sql);
        connection.query(sql, function(queryErr, results){
            connection.release();
            if(queryErr) {
                console.log('YjxThirdPartyUserModel.checkWechatUserIsExistsForV1_0 queryErr: ' + queryErr);
            }
            var user = null;
            if (results && results.length >=0) {
                user = results[0];
            }
            return callback(queryErr, user);
        });
    });
};

/**
 * 为修正1.0 iOS 微信登录误传 openId 至 unionId 的位置所做的兼容操作, 1.0.1 用于检测微信用户是否存在
 *
 * @author 王俊
 * @date 2017-12-26
 *
 * @param unionId    微信用户的 unionId
 * @param openId    微信用户的 openId
 * @param callback  回调
 *          error:  查询失败
 *          user:   可能存在可能不存在
 *             tpu.*        第三方用户所有列
 *             rightUser:   field1 存入的是 unionId 则 rightUser = 1
 */
YjxThirdPartyUserModel.prototype.checkWechatUserIsExistsForV1_0_1 = function (unionId, openId, callback) {

    pool.pool.getConnection(function(getConnectErr, connection) {
        if (getConnectErr) {
            console.log('YjxThirdPartyUserModel.checkWechatUserIsExistsForV1_0_1 getConnectErr: ' + getConnectErr);
            return callback(getConnectErr, null);
        }
        var sql = ' SELECT ytpu.*, ' +
            //              field1 为 opend, field2 为 空或 unionId 均认为该数据异常, 需要修正
            '        IF ((ytpu.field1 = "'+openId+'") || (ytpu.field2 is null) || ytpu.field2 = "'+unionId+'",0,1) AS rightUser ' +
            ' FROM yjx.yjx_third_party_user ytpu ' +
            ' WHERE ytpu.del_flg=0 ' +
            '   AND ytpu.field1 IN ("'+openId+'","'+unionId+'")' +
            '   AND ytpu.account_type = 20 ';

        console.log(sql);
        connection.query(sql, function(queryErr, results){
            connection.release();
            if(queryErr) {
                console.log('YjxThirdPartyUserModel.checkWechatUserIsExistsForV1_0_1 queryErr: ' + queryErr);
            }
            var user = null;
            if (results && results.length >=0) {
                user = results[0];
            }
            return callback(queryErr, user);
        });
    });
};


/**
 * 检测用户是否注册过
 * @author 毛凯
 * @date 2017-12-26
 *
 * @param mobile    手机号
 * @param callback  回调
 *          error:  查询失败
 *          user:   可能存在可能不存在
 */
YjxThirdPartyUserModel.prototype.checkUserMobile = function (mobile, callback) {

    pool.pool.getConnection(function(getConnectErr, connection) {
        if (getConnectErr) {
            console.log('YjxThirdPartyUserModel.checkUserMobile getConnectErr: ' + getConnectErr);
            return callback(getConnectErr, null);
        }
        var sql = "	SELECT	" +
                "	  *	" +
                "	FROM	" +
                "	  yjx.yjx_third_party_user ytpu	" +
                "	WHERE ytpu.del_flg = 0	" +
                "	  AND ytpu.field1 = '"+mobile+"' " ;
            console.log(sql);
        connection.query(sql, function(queryErr, results){
            connection.release();
            if(queryErr) {
                console.log('YjxThirdPartyUserModel.checkWechatUserIsExistsForV1_0 queryErr: ' + queryErr);
            }
            var user = null;
            if (results && results.length >=0) {
                user = results[0];
            }
            return callback(queryErr, user);
        });
    });
};


/**
 * 绑定用户手机号
 * @author 毛凯
 * @date 2017-12-26
 *
 * @param userId   用户Id
 * @param mobile    手机号
 * @param callback  回调
 *          error:  查询失败
 *          user:   可能存在可能不存在
 */
YjxThirdPartyUserModel.prototype.bindMobileToUser = function (userId,mobile, callback) {

    pool.pool.getConnection(function(getConnectErr, connection) {
        if (getConnectErr) {
            console.log('YjxThirdPartyUserModel.bindMobileToUser getConnectErr: ' + getConnectErr);
            return callback(getConnectErr, null);
        }
        var sql = "	INSERT INTO yjx.yjx_third_party_user(	" +
            "	  user_id,	" +
            "	  account_type,	" +
            "	  field1,	" +
            "	  field2,	" +
            "	  create_time,	" +
            "	  update_time,	" +
            "	  update_by,	" +
            "	  del_flg	" +
            "	)	" +
            "	VALUES	" +
            "	  (	" +
            "	    '"+userId+"',	" +
            "	    '10',	" +
            "	    '"+mobile+"',	" +
            "	    '+86',	" +
            "	    NOW(),	" +
            "	    NOW(),	" +
            "	    '"+userId+"',	" +
            "	     0	   " +
            "	  )	" ;
            console.log(sql);
        connection.query(sql, function(queryErr, results){
            connection.release();
            if(queryErr) {
                console.log('YjxThirdPartyUserModel.bindMobileToUser queryErr: ' + queryErr);
            }
            return callback(queryErr, results);
        });
    });
};

/**
 * 检测用户身份证是否存在
 * @author 毛凯
 * @date 2017-12-26
 *
 * @param realName   真实姓名
 * @param idCardNum  身份证号
 * @param callback  回调
 *          error:  查询失败
 *          user:   可能存在可能不存在
 */
YjxThirdPartyUserModel.prototype.checkUserIdCardNum  = function (realName,idCardNum, callback) {

    pool.pool.getConnection(function(getConnectErr, connection) {
        if (getConnectErr) {
            console.log('YjxThirdPartyUserModel.bindMobileToUser getConnectErr: ' + getConnectErr);
            return callback(getConnectErr, null);
        }
        var sql = "SELECT  COUNT(0) AS `count` FROM yjx.yjx_third_party_user ytpu WHERE ytpu.field1 = '"+idCardNum+"' AND ytpu.field2 = '"+realName+"' AND ytpu.del_flg = 0";
        console.log(sql);
        connection.query(sql, function(queryErr, results){
            connection.release();
            if(queryErr) {
                console.log('YjxThirdPartyUserModel.bindMobileToUser queryErr: ' + queryErr);
            }
            return callback(queryErr, results[0].count);
        });
    });
};



module.exports = YjxThirdPartyUserModel;